#!/bin/bash

# 工程实践平台环境安装脚本
# 适用于 Ubuntu 20.04+ / Debian 11+ 系统
# 使用方法: sudo bash install-environment.sh

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本需要root权限运行，请使用: sudo bash $0"
        exit 1
    fi
}

# 检查系统版本
check_system() {
    log_info "检查系统版本..."
    
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        OS=$NAME
        VER=$VERSION_ID
    else
        log_error "无法检测系统版本"
        exit 1
    fi
    
    log_info "检测到系统: $OS $VER"
    
    # 检查是否为支持的版本
    if [[ "$OS" == "Ubuntu" && "$VER" < "20.04" ]]; then
        log_warning "Ubuntu版本过低，建议使用20.04或更高版本"
    elif [[ "$OS" == "Debian GNU/Linux" && "$VER" < "11" ]]; then
        log_warning "Debian版本过低，建议使用11或更高版本"
    fi
}

# 更新系统包
update_system() {
    log_info "更新系统包..."
    apt update && apt upgrade -y
    log_success "系统包更新完成"
}

# 安装基础工具
install_basic_tools() {
    log_info "安装基础工具..."
    apt install -y curl wget git unzip software-properties-common \
                   apt-transport-https ca-certificates gnupg lsb-release \
                   htop vim net-tools
    log_success "基础工具安装完成"
}

# 安装Java 17
install_java() {
    log_info "安装Java 17..."
    
    if command -v java &> /dev/null; then
        JAVA_VERSION=$(java -version 2>&1 | head -n 1)
        log_info "Java已安装: $JAVA_VERSION"
        
        # 检查Java版本
        if [[ $JAVA_VERSION == *"17"* ]]; then
            log_success "Java 17已安装"
            return 0
        else
            log_warning "检测到其他版本的Java，将安装Java 17"
        fi
    fi
    
    # 安装OpenJDK 17
    apt install -y openjdk-17-jdk openjdk-17-jre
    
    # 设置JAVA_HOME
    if [ -z "$JAVA_HOME" ]; then
        echo 'export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64' >> /etc/environment
        echo 'export PATH=$JAVA_HOME/bin:$PATH' >> /etc/environment
        export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
        export PATH=$JAVA_HOME/bin:$PATH
    fi
    
    log_success "Java 17安装完成"
}

# 安装Maven
install_maven() {
    log_info "安装Maven..."
    
    if command -v mvn &> /dev/null; then
        MAVEN_VERSION=$(mvn -version | head -n 1)
        log_info "Maven已安装: $MAVEN_VERSION"
        return 0
    fi
    
    apt install -y maven
    log_success "Maven安装完成"
}

# 安装Docker
install_docker() {
    log_info "安装Docker..."
    
    if command -v docker &> /dev/null; then
        DOCKER_VERSION=$(docker --version)
        log_info "Docker已安装: $DOCKER_VERSION"
        return 0
    fi
    
    # 安装Docker官方版本
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
    
    apt update
    apt install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    
    # 启动Docker服务
    systemctl start docker
    systemctl enable docker
    
    # 将当前用户添加到docker组
    usermod -aG docker $SUDO_USER
    
    log_success "Docker安装完成"
}

# 配置Docker镜像加速器
configure_docker_mirrors() {
    log_info "配置Docker镜像加速器..."
    
    mkdir -p /etc/docker
    
    cat > /etc/docker/daemon.json << 'EOF'
{
  "registry-mirrors": [
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com",
    "https://registry.docker-cn.com"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "3"
  }
}
EOF
    
    # 重启Docker服务
    systemctl restart docker
    
    log_success "Docker镜像加速器配置完成"
}

# 安装Docker Compose
install_docker_compose() {
    log_info "安装Docker Compose..."
    
    if command -v docker-compose &> /dev/null; then
        COMPOSE_VERSION=$(docker-compose --version)
        log_info "Docker Compose已安装: $COMPOSE_VERSION"
        return 0
    fi
    
    # 使用apt安装Docker Compose插件
    apt install -y docker-compose-plugin
    
    # 创建docker-compose命令的软链接（兼容性）
    if [ ! -f /usr/local/bin/docker-compose ]; then
        ln -sf /usr/libexec/docker/cli-plugins/docker-compose /usr/local/bin/docker-compose
    fi
    
    log_success "Docker Compose安装完成"
}

# 创建项目目录
create_project_directories() {
    log_info "创建项目目录..."
    
    mkdir -p /opt/practice-platform/{logs,backups,users,mysql-data,redis-data}
    
    # 设置目录权限
    chown -R $SUDO_USER:$SUDO_USER /opt/practice-platform
    chmod -R 755 /opt/practice-platform
    
    log_success "项目目录创建完成"
}

# 创建启动脚本
create_startup_scripts() {
    log_info "创建启动脚本..."
    
    cat > /opt/practice-platform/start.sh << 'EOF'
#!/bin/bash

# 工程实践平台启动脚本

set -e

echo "=========================================="
echo "启动工程实践平台..."
echo "=========================================="

# 检查Docker服务状态
if ! systemctl is-active --quiet docker; then
    echo "启动Docker服务..."
    sudo systemctl start docker
fi

# 检查MySQL容器状态
if ! docker ps | grep -q practice-platform-mysql; then
    echo "启动MySQL服务..."
    cd /opt/practice-platform
    docker-compose up -d mysql
    echo "等待MySQL启动..."
    sleep 30
fi

# 启动主应用
echo "启动主应用..."
cd /opt/practice-platform

# 检查JAR文件是否存在
if [ ! -f "app.jar" ]; then
    echo "错误: app.jar文件不存在，请先构建项目"
    exit 1
fi

# 启动应用
nohup java -jar app.jar --spring.profiles.active=prod > logs/app.log 2>&1 &
echo $! > app.pid

echo "应用启动完成，PID: $(cat app.pid)"
echo "查看日志: tail -f logs/app.log"
echo "访问地址: http://localhost:8080"
EOF
    
    chmod +x /opt/practice-platform/start.sh
    chown $SUDO_USER:$SUDO_USER /opt/practice-platform/start.sh
    
    log_success "启动脚本创建完成"
}

# 创建停止脚本
create_stop_scripts() {
    log_info "创建停止脚本..."
    
    cat > /opt/practice-platform/stop.sh << 'EOF'
#!/bin/bash

# 工程实践平台停止脚本

echo "=========================================="
echo "停止工程实践平台..."
echo "=========================================="

cd /opt/practice-platform

# 停止主应用
if [ -f "app.pid" ]; then
    PID=$(cat app.pid)
    if kill -0 $PID 2>/dev/null; then
        echo "停止应用进程 (PID: $PID)..."
        kill $PID
        rm -f app.pid
        echo "应用已停止"
    else
        echo "应用进程不存在"
        rm -f app.pid
    fi
else
    echo "未找到应用PID文件"
fi

# 停止Docker服务
echo "停止Docker服务..."
docker-compose down 2>/dev/null || true

echo "平台已停止"
EOF
    
    chmod +x /opt/practice-platform/stop.sh
    chown $SUDO_USER:$SUDO_USER /opt/practice-platform/stop.sh
    
    log_success "停止脚本创建完成"
}

# 创建状态检查脚本
create_status_scripts() {
    log_info "创建状态检查脚本..."
    
    cat > /opt/practice-platform/status.sh << 'EOF'
#!/bin/bash

# 工程实践平台状态检查脚本

echo "=========================================="
echo "工程实践平台状态检查"
echo "=========================================="

cd /opt/practice-platform

# 检查应用状态
if [ -f "app.pid" ]; then
    PID=$(cat app.pid)
    if kill -0 $PID 2>/dev/null; then
        echo "✅ 主应用正在运行，PID: $PID"
        echo "内存使用: $(ps -o rss= -p $PID | awk '{print $1/1024 " MB"}')"
        echo "CPU使用: $(ps -o %cpu= -p $PID)%"
    else
        echo "❌ 主应用未运行"
        rm -f app.pid
    fi
else
    echo "❌ 主应用未运行"
fi

# 检查端口监听
echo "端口检查:"
if netstat -tlnp 2>/dev/null | grep -q ":8080"; then
    echo "✅ 端口8080正在监听"
else
    echo "❌ 端口8080未监听"
fi

# 检查Docker容器状态
echo "Docker容器状态:"
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep practice-platform || echo "无相关容器运行"

# 检查磁盘使用
echo "磁盘使用情况:"
df -h /opt/practice-platform
EOF
    
    chmod +x /opt/practice-platform/status.sh
    chown $SUDO_USER:$SUDO_USER /opt/practice-platform/status.sh
    
    log_success "状态检查脚本创建完成"
}

# 安装完成后的提示
show_completion_message() {
    log_success "=========================================="
    log_success "环境安装完成！"
    log_success "=========================================="
    echo
    echo "下一步操作："
    echo "1. 重新登录或执行: newgrp docker"
    echo "2. 构建项目: mvn clean package -DskipTests"
    echo "3. 复制JAR文件: cp target/demo02-*.jar /opt/practice-platform/app.jar"
    echo "4. 启动平台: /opt/practice-platform/start.sh"
    echo "5. 检查状态: /opt/practice-platform/status.sh"
    echo
    echo "项目目录: /opt/practice-platform"
    echo "日志目录: /opt/practice-platform/logs"
    echo "用户数据: /opt/practice-platform/users"
    echo
    echo "如有问题，请查看日志文件或联系技术支持"
}

# 主函数
main() {
    echo "=========================================="
    echo "工程实践平台环境安装脚本"
    echo "=========================================="
    echo
    
    # 检查系统要求
    check_root
    check_system
    
    # 安装环境
    update_system
    install_basic_tools
    install_java
    install_maven
    install_docker
    configure_docker_mirrors
    install_docker_compose
    
    # 创建项目结构
    create_project_directories
    create_startup_scripts
    create_stop_scripts
    create_status_scripts
    
    # 显示完成信息
    show_completion_message
}

# 执行主函数
main "$@" 